#文件的操作，因为要把读取文件写成一个函数，调用yaml文件中的内容
import yaml
import os
basepath= os.path.dirname(os.path.dirname(__file__))#
from loguru import logger
from config.project_baseinfo import *
# print(basepath)
def read_yaml(filepath):
    '''

    :param filepath:yaml 文件路径
    :return: yaml文件中的内容
    '''
    with open(basepath + '/'+filepath,'r',encoding='utf-8')as f:
        data = yaml.safe_load(f)
        if data is None:
            return {}
        else:
            return data

def write_extract_variable(key,value):
    '''
    导入变量方法，写到文件中
    :param  key:变量名
    :param  value:变量的值
    :return: 不返回任何内容
    '''
    with open(basepath + '/data/extract_variable.yaml','a',encoding='utf-8') as f:
        data = {key:value}
        yaml.dump(data,stream=f,allow_unicode=True)

def clear_extract_variable():
    '''
    每次运行前清空文件
    :return:
    '''
    with open(basepath + '/data/extract_variable.yaml','w',encoding='utf-8') as f:
        f.truncate()
def read_extract_variable(key):
    '''

    :param key: 变量名称
    :return: 值
    '''
    with open(basepath + '/data/extract_variable.yaml','r',encoding='utf-8') as f:
        try:
            data = yaml.safe_load(f)
            return data[key]
        except Exception as e:
            logger.error(f'获取变量失败{e}')
            return ''

def write_buy_system_shopping_variable(key,value):
    '''
    导入变量方法，写到文件中
    :param  key:变量名
    :param  value:变量的值
    :return: 不返回任何内容
    '''
    with open(basepath + '/data/buy_system_data.yaml','a',encoding='utf-8') as f:
        data = {key:value}
        yaml.dump(data,stream=f,allow_unicode=True)
def clear_buy_system_shopping_variable():
    '''
    每次运行前清空文件
    :return:
    '''
    with open(basepath + '/data/buy_system_data.yaml','w',encoding='utf-8') as f:
        f.truncate()

def read_buy_system_shopping_variable(key):
    '''

    :param key: 变量名称
    :return: 值
    '''
    with open(basepath + '/data/buy_system_data.yaml','r',encoding='utf-8') as f:
        try:
            data = yaml.safe_load(f)
            return data[key]
        except Exception as e:
            logger.error(f'获取变量失败{e}')
            return ''

